package com.qf.test;

import com.qf.util.ElasticsearchUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

import java.io.IOException;

/**
 * 基础查询
 */
public class Demo2 {


    @Test
    public void match() throws IOException {
        //1. 创建Request对象
        SearchRequest request = new SearchRequest();

        //2. 封装Request对象数据
        //2.1 设置index名称
        request.indices("sms-logs-index");
        //2.2 设置查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchQuery("smsContent","刘红先生"));
        //2.3 设置分页信息
        sourceBuilder.from(0);
        sourceBuilder.size(2);
        //2.4 设置排序规则
        sourceBuilder.sort("fee", SortOrder.DESC);
        request.source(sourceBuilder);


        //3. 发送Request到ES,获取Response
        SearchResponse resp = ElasticsearchUtil.getClient().search(request, RequestOptions.DEFAULT);

        //4. 解析Response获取相应数据
        //4.1 获取数据总条数
        System.out.println("数据总条数为:" + resp.getHits().getTotalHits().value);
        //4.2 获取到具体数据
        System.out.println("具体数据如下:");
        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }

    }
}
